#! /usr/bin/env python
# -*- coding: utf-8 -*-


import os
import sqlite3
import sys
import hashlib
#reload(sys)
#sys.setdefaultencoding('utf-8')

def sanity_check():
    if len(sys.argv) != 3:
        return False

    if not os.path.isdir(sys.argv[1]):
        print(sys.argv[1] + " is not a directory!")
        return False

    if not os.path.exists(sys.argv[2]):
        print(sys.argv[2] + " NOT exist!")
        return False

    return True

def print_usage():
    print("Usage:")
    print("   ", sys.argv[0], " DIR DB")
    print("Description:")
    print("   update DB after deleting files in DIR, it's used when:")
    print("   1. use find_dupfiles.py to create DB according to DIR")
    print("   2. delete some files in DIR so it isn't corresponding with DB")

def update_db(tdir, tdb):
    con = sqlite3.connect(tdb)
    con.text_factory = str
    cur = con.cursor()

    cur.execute("SELECT filename FROM files")
    all = cur.fetchall()

    for i in all:
        filename = i[0]
        if not os.path.exists(filename):
            print(filename)
            cur.execute('''DELETE FROM files where filename = ?''',(filename,)) # delete from db


    con.commit()
    con.close()



if __name__ == "__main__":
    if not sanity_check():
        print_usage()
        exit(1)

    tdir = sys.argv[1]
    tdb = sys.argv[2]

    update_db(tdir, tdb)
